package com.yuncheng.spcyApi.spcyService;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.mapper.SpcySqsxLjzlMydBasicMapper;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.myd.SpcyMyddcConstant;
import com.yuncheng.spcyApi.constant.wjml.WjmlConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.mapper.DictItemMapper;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.LocalFileUploadUtils;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.spcyApi.utils.WordPdfUtils;
import com.yuncheng.spcyApi.vo.common.Result;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import utils.DateConversionUtils;
import utils.Util;
import utils.WordDocxReplaceUtils;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 检查员廉洁自律和满意度基本信息接口
 * @author hua
 */
@Service
public class SpcyMyddcService {

    private static final Logger log = LoggerFactory.getLogger(SpcyMyddcService.class);

    @Resource
    private ISpcySqsxLjzlMydBasicService spcySqsxLjzlMydBasicService;

    @Resource
    private ISpcySqsxLjzlMydHcypjService spcySqsxLjzlMydHcypjService;

    @Resource
    private ISpcySqsxLjzlMydZxpjService spcySqsxLjzlMydZxpjService;

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    private BusService busService;

    @Resource
    private DictItemMapper dictItemMapper;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private BusinessConstant businessConstant;

    @Resource
    private SpcySqsxLjzlMydBasicMapper spcySqsxLjzlMydBasicMapper;

    /**
     * 获取初始化廉洁自律和满意度调查问卷
     * @param sqsxid
     * @return
     */
    public Result initHcyLjzlMydBasic(String sqsxid) {
        boolean isExistJcyPj = true;
        String mydId = "";

        List<SpcySqsxLjzlMydHcypj> jcyPjList = new ArrayList<>();
        List<SpcySqsxLjzlMydZxpj> zxpjList = new ArrayList<>();

        /** 验证是否已经存在问卷 */
        List<SpcySqsxLjzlMydBasic> mydList = spcySqsxLjzlMydBasicService.list(new LambdaQueryWrapper<SpcySqsxLjzlMydBasic>()
                .eq(SpcySqsxLjzlMydBasic::getFsqsxid, sqsxid));
        if (CollectionUtils.isNotEmpty(mydList)){
            SpcySqsxLjzlMydBasic myd = mydList.get(0);
            mydId = myd.getId();

            /*if (myd.getFsftj().equals(SpcyMyddcConstant.LJZL_MYD_SFTJ_YES)){
                return Result.error("该问卷已经提交过了");
            }*/

            jcyPjList = spcySqsxLjzlMydHcypjService.list(new LambdaQueryWrapper<SpcySqsxLjzlMydHcypj>()
                    .eq(SpcySqsxLjzlMydHcypj::getFljzlmydjbxxid, mydId)
                    .orderByAsc(SpcySqsxLjzlMydHcypj::getFxh));
            if (CollectionUtils.isNotEmpty(jcyPjList)){
                isExistJcyPj = false;
            }
        }
        else {
            /** 不存在初始化 */
            SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
            SpcySqsxLjzlMydBasic myd = new SpcySqsxLjzlMydBasic();
            mydId = GetUuIdUtils.ReplaceUuId();
            myd.setId(mydId);
            myd.setFsqsxid(sqsxid);
            if (sqsx != null) {
                myd.setFgzdw(sqsx.getFqymc());
                myd.setFqymc(sqsx.getFqymc());
                myd.setFxz(SpcyMyddcConstant.getLjzlMydXzByYwfl(sqsx.getFywflcode()));
                if (sqsx.getFcykssj() != null && sqsx.getFcyjssj() != null) {
                    String kssj = DateConversionUtils.DateToStringNew(sqsx.getFcykssj());
                    String jssj = DateConversionUtils.DateToStringNew(sqsx.getFcyjssj());
                    myd.setFjcsj(kssj + "至" + jssj);
                }
            }
            myd.setFsftj(SpcyMyddcConstant.LJZL_MYD_SFTJ_NO);


            /** 问卷标题和描述 */
            List<String> mydTitleList = dictItemMapper.getDictItemListByCode(SpcyMyddcConstant.DICT_CODE_MYD_WJ_TITLE);
            myd.setFwjbt(mydTitleList.get(0));
            myd.setFwjms(mydTitleList.get(1));
            myd.setFtxrq(new Date());

            spcySqsxLjzlMydBasicService.save(myd);
        }

        /** 对中心评价-等级 */
        List<String> zxpjOptionList = null;

        /** 初始化问卷对检查组的评价 */
        if (isExistJcyPj){
            zxpjOptionList = dictItemMapper.getDictItemListByCode(SpcyMyddcConstant.DICT_CODE_ZXPJ_DJ);

            List<SpcySqsxXpjl> tyXpXpjlList = busService.getTyXpXpjlList(sqsxid, SpcyConstant.FLOW_TYPE_CY);
            if (CollectionUtils.isNotEmpty(tyXpXpjlList)) {
                SpcySqsxLjzlMydHcypj jcypj = null;
                int i = 0;
                for (SpcySqsxXpjl xpjl : tyXpXpjlList) {
                    i = i + 1;
                    jcypj = new SpcySqsxLjzlMydHcypj();
                    jcypj.setId(GetUuIdUtils.ReplaceUuId());
                    jcypj.setFljzlmydjbxxid(mydId);
                    jcypj.setFxh(i);
                    jcypj.setFjcyxm(xpjl.getFjcyxm());
                    jcypj.setFjcysf(xpjl.getFssk());
                    jcypj.setCreateTime(new Date());

                    jcypj.setFoption(StringPatternUtils.convertListToDhString(zxpjOptionList));

                    jcypj.setCreateBy(xpjl.getFuserid());
                    jcypj.setUpdateBy(xpjl.getFuserid());
                    jcyPjList.add(jcypj);
                }
                spcySqsxLjzlMydHcypjService.saveBatch(jcyPjList);
            }
        }

        /** 初始化问卷对中心的评价 */
        if (isExistJcyPj) {
            List<String> zxpjTitleList = dictItemMapper.getDictItemListByCode(SpcyMyddcConstant.DICT_CODE_ZXPJ_TITLE);
            for (int i = 0; i< zxpjTitleList.size(); i++){
                SpcySqsxLjzlMydZxpj zxpj = new SpcySqsxLjzlMydZxpj();
                zxpj.setId(GetUuIdUtils.NotReplaceUuId());
                zxpj.setFljzlmydjbxxid(mydId);
                zxpj.setFpjbt(zxpjTitleList.get(i));
                zxpj.setFxh(i+1);

                zxpj.setFoption(StringPatternUtils.convertListToDhString(zxpjOptionList));
                zxpj.setCreateTime(new Date());

                zxpjList.add(zxpj);
            }
            spcySqsxLjzlMydZxpjService.saveBatch(zxpjList);
        }

        return Result.ok(this.querySqsxLjzlMydXq(sqsxid, mydList, jcyPjList, zxpjList));
    }

    /**
     * 获取廉洁自律和满意度调查问卷详情
     */
    public Map querySqsxLjzlMydXq(String sqsxid){
        return this.querySqsxLjzlMydXq(sqsxid, null, null, null);
    }
    public Map getMydInfoById(String id){
        List<SpcySqsxLjzlMydBasic> mydList = spcySqsxLjzlMydBasicService.list(new LambdaQueryWrapper<SpcySqsxLjzlMydBasic>().eq(SpcySqsxLjzlMydBasic::getId, id));
        return this.querySqsxLjzlMydXq(id, mydList, null, null);
    }
    public Map querySqsxLjzlMydXq(String sqsxid, List<SpcySqsxLjzlMydBasic> mydList, List<SpcySqsxLjzlMydHcypj> jcyPjList, List<SpcySqsxLjzlMydZxpj> zxPjList){
        Map resultMap = new HashMap();

        SpcySqsxLjzlMydBasic myd = null;
        String mydId = "";

        /** 满意度基本信息 */
        if (CollectionUtil.isEmpty(mydList)) {
            mydList = spcySqsxLjzlMydBasicService.list(new LambdaQueryWrapper<SpcySqsxLjzlMydBasic>()
                    .eq(SpcySqsxLjzlMydBasic::getFsqsxid, sqsxid));
        }

        if (CollectionUtils.isNotEmpty(mydList)){
            myd = mydList.get(0);
            mydId = mydList.get(0).getId();
        }
        resultMap.put("myd", myd);

        /** 对中心的评价 */
        if (CollectionUtil.isEmpty(zxPjList)) {
            zxPjList = spcySqsxLjzlMydZxpjService.list(new LambdaQueryWrapper<SpcySqsxLjzlMydZxpj>()
                    .eq(SpcySqsxLjzlMydZxpj::getFljzlmydjbxxid, mydId)
                    .orderByAsc(SpcySqsxLjzlMydZxpj::getFxh));
        }

        resultMap.put("zxpjList", zxPjList);


        /** 对检查组的评价 */
        if (CollectionUtil.isEmpty(jcyPjList)) {
            jcyPjList = spcySqsxLjzlMydHcypjService.list(new LambdaQueryWrapper<SpcySqsxLjzlMydHcypj>()
                    .eq(SpcySqsxLjzlMydHcypj::getFljzlmydjbxxid, mydId)
                    .orderByAsc(SpcySqsxLjzlMydHcypj::getFxh));
        }

        /** 对检查组评价的标题 */
        resultMap.put("jcyPjList", jcyPjList);

        return resultMap;
    }

    /**
     * 同步更新检查组评价表
     * */
    public void syncUpdateMydJcyPj(String sqsxid, Date jckssj, Date jcjssj, List<String> removeUserIdList, List<String> addUserIdList){
        List<String> list = spcySqsxLjzlMydBasicMapper.selectIdByFsqsxid(sqsxid);
        if (CollectionUtil.isEmpty(list)){
            return;
        }

        // 同步满意度调查表-检查时间
        syncUpdateJcsjInfo(sqsxid, jckssj, jcjssj);

        if (CollectionUtil.isNotEmpty(removeUserIdList)) {
            spcySqsxLjzlMydHcypjService.remove(new LambdaQueryWrapper<SpcySqsxLjzlMydHcypj>()
                    .in(SpcySqsxLjzlMydHcypj::getCreateBy, removeUserIdList));
        }

        if (CollectionUtil.isEmpty(addUserIdList)){
            return;
        }

        List<SpcySqsxLjzlMydHcypj> pjList = spcySqsxLjzlMydHcypjService.list(new LambdaQueryWrapper<SpcySqsxLjzlMydHcypj>()
                .eq(SpcySqsxLjzlMydHcypj::getFljzlmydjbxxid, list.get(0)));

        List<SpcySqsxXpjl> tyXpXpjlList = busService.getTyXpXpjlList(sqsxid, SpcyConstant.FLOW_TYPE_CY);

        int order = pjList.size() + 1;

        List<SpcySqsxLjzlMydHcypj> jcyPjList = new ArrayList<>();
        List<String> zxpjOptionList = null;
        for (SpcySqsxXpjl xpjl : tyXpXpjlList){

            List<SpcySqsxLjzlMydHcypj> filterList = pjList.stream()
                    .filter(f -> f.getFjcysf().equals(xpjl.getFssk()) && f.getFjcyxm().equals(xpjl.getFjcyxm()))
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(filterList)){
                continue;
            }

            if (CollectionUtil.isEmpty(zxpjOptionList)) {
                zxpjOptionList = dictItemMapper.getDictItemListByCode(SpcyMyddcConstant.DICT_CODE_ZXPJ_DJ);
            }

            SpcySqsxLjzlMydHcypj jcypj = new SpcySqsxLjzlMydHcypj();
            jcypj.setId(GetUuIdUtils.ReplaceUuId());
            jcypj.setFljzlmydjbxxid(list.get(0));
            jcypj.setFxh(order+1);
            jcypj.setFjcyxm(xpjl.getFjcyxm());
            jcypj.setFjcysf(xpjl.getFssk());
            jcypj.setCreateTime(new Date());

            jcypj.setFoption(StringPatternUtils.convertListToDhString(zxpjOptionList));

            jcypj.setCreateBy(xpjl.getFuserid());
            jcypj.setUpdateBy(xpjl.getFuserid());

            jcyPjList.add(jcypj);
            order++;
        }

        if (CollectionUtil.isNotEmpty(jcyPjList)) {
            spcySqsxLjzlMydHcypjService.saveBatch(jcyPjList);
        }
    }

    /**
     * 同步满意度调查表-检查时间
     * */
    private void syncUpdateJcsjInfo(String sqsxid, Date jckssj, Date jcjssj){
        if (jckssj == null || jcjssj == null){
            return;
        }

        String jcsj = DateConversionUtils.DateToStringNew(jckssj);
        jcsj += "至";
        jcsj += DateConversionUtils.DateToStringNew(jcjssj);

        LambdaUpdateWrapper<SpcySqsxLjzlMydBasic> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcySqsxLjzlMydBasic::getFsqsxid, sqsxid);

        SpcySqsxLjzlMydBasic updateBean = new SpcySqsxLjzlMydBasic();
        updateBean.setFjcsj(jcsj);
        spcySqsxLjzlMydBasicService.update(updateBean, updateWrapper);

    }

    /**
     * 初始化-满意度调查问卷模板问卷
     */
    private String initMydTableTemplate(SpcySqsxLjzlMydBasic myd){
        /** 模板字段Map */
        HashMap<String, Object> templateField = new HashMap<>();

        /** 基本信息 */
        templateField.put("flxdh", myd.getFlxdh());
        templateField.put("fqyfzr", myd.getFqyfzr());
        templateField.put("fqymc", myd.getFqymc());
        templateField.put("fgzdw", myd.getFgzdw());
        templateField.put("fyjhyq", myd.getFyjhyq());

        if (myd.getFtxrq() != null) {
            templateField.put("ftxrq", DateConversionUtils.DateToStringNew(myd.getFtxrq()));
        }else {
            templateField.put("ftxrq", "");
        }
        templateField.put("fjcsj", myd.getFjcsj());

        /** 企业类型 ☑ */
        if (StringUtils.isNotBlank(myd.getFxz())){
            List<String> qylxList = dictItemMapper.getDictItemListByCode(SpcyMyddcConstant.DICT_CODE_MYD_QY_LX);
            String xz = "";
            for (String lx : qylxList){
                xz += StringUtils.isNotBlank(xz) ? "  " : "";
                if (lx.equals(myd.getFxz()) && lx.equals(SpcyMyddcConstant.MYD_QT_XZ)){
                    xz += "√其他（请填写：" + Optional.ofNullable(myd.getFqtxz()).orElseGet(()->"________") + "）";
                }else if (lx.equals(myd.getFxz())){
                    xz += "√" + lx;
                }else {
                    if (lx.equals(SpcyMyddcConstant.MYD_QT_XZ)){
                        xz += "□其他（请填写：________）";
                    }else {
                        xz += "□" + lx;
                    }
                }
            }
            templateField.put("xz", xz);
        }else {
            List<String> qylxList = dictItemMapper.getDictItemListByCode(SpcyMyddcConstant.DICT_CODE_MYD_QY_LX);
            String xz = "";
            for (String lx : qylxList){
                xz += StringUtils.isNotBlank(xz) ? "  " : "";
                xz += "□" + lx;
            }
            templateField.put("xz", xz);
        }

        /** 对中心的评价 */
        List<Map<String, Object>> questionsMapList = new ArrayList<>();
        List<SpcySqsxLjzlMydZxpj> zxpjList = spcySqsxLjzlMydZxpjService.list(new LambdaQueryWrapper<SpcySqsxLjzlMydZxpj>()
                .eq(SpcySqsxLjzlMydZxpj::getFljzlmydjbxxid, myd.getId())
                .orderByAsc(SpcySqsxLjzlMydZxpj::getFxh));
        if (CollectionUtil.isNotEmpty(zxpjList)) {
            for (SpcySqsxLjzlMydZxpj zxpj : zxpjList) {

                Map<String, Object> questionMap = new HashMap<>();
                questionMap.put("question", zxpj.getFxh() + ". " + zxpj.getFpjbt());

                String answer = "";
                List<String> optionList = StringPatternUtils.getListByIds(zxpj.getFoption());
                for (String option : optionList){
                    answer += StringUtils.isNotBlank(answer) ? "  " : "";
                    if (StringUtils.isNotBlank(zxpj.getFpjjg()) && option.equals(zxpj.getFpjjg())){
                        answer += "√" + option;
                    }else {
                        answer += "□" + option;
                    }
                }
                questionMap.put("answer", answer);
                questionsMapList.add(questionMap);

                /** 选项标题 */
                /*templateField.put("t" + zxpj.getFxh(), zxpj.getFpjbt());
                String answer = "";*/

                /** 选项字段 */
                /*List<String> optionList = StringPatternUtils.getListByIds(zxpj.getFoption());
                for (String option : optionList){
                    answer += StringUtils.isNotBlank(answer) ? "  " : "";
                    if (StringUtils.isNotBlank(zxpj.getFpjjg()) && option.equals(zxpj.getFpjjg())){
                        answer += "☑" + option;
                    }else {
                        answer += "□" + option;
                    }
                }
                templateField.put("option" + zxpj.getFxh(), answer);*/
            }
        }
        templateField.put("questions", questionsMapList);

        /** 检查组评价列表 */
        List<SpcySqsxLjzlMydHcypj> jcyPjList = spcySqsxLjzlMydHcypjService.list(new LambdaQueryWrapper<SpcySqsxLjzlMydHcypj>()
                .eq(SpcySqsxLjzlMydHcypj::getFljzlmydjbxxid, myd.getId())
                .orderByAsc(SpcySqsxLjzlMydHcypj::getFxh));
        templateField.put("jcyList", jcyPjList);

//        Configure config = Configure.builder().bind("jcyList", new HackLoopTableRenderPolicy()).build();

        ConfigureBuilder builder = Configure.builder();
        builder.bind("jcyList", new HackLoopTableRenderPolicy());

        String orgUrl = businessConstant.UPLOAD_FILE_ROOT + "/" + WjmlConstant.Template_File_Mdcdcwj;
        String destWordUrl = localFileUploadUtils.getTempFileRootUrl() + "/";
        destWordUrl += GetUuIdUtils.NotReplaceUuId() + Util.getWjHz(orgUrl);
        WordDocxReplaceUtils.docxConfigureReplace(orgUrl, destWordUrl, builder.useSpringEL().build(), templateField);

        return destWordUrl;
    }

    /**
     * 下载-满意度调查问卷模板文件-文档
     */
    public void downMydTableTemplate(SpcySqsxLjzlMydBasic myd, HttpServletResponse response) throws IOException {
        String destWordUrl = "";
        try {
            destWordUrl = this.initMydTableTemplate(myd);
        }catch (Exception e){
            log.error("初始化-满意度调查问卷模板问卷错误：{}", e.getMessage());
        }

        if (StringUtils.isBlank(destWordUrl)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
//            response.getWriter().write("没有相匹配的事项参数！");
            PrintWriter writer = response.getWriter();
            writer.println("问卷模板错误！");
            writer.close(); // 不要忘记关闭PrintWriter

            return;
        }

        localFileUploadUtils.ejzLocalFileByZdyFile(new File(destWordUrl), response);
    }

    /**
     * 下载-满意度调查问卷模板文件-PDF
     * @param isDownPdf 是否下载pdf
     */
    public void downMydTableTemplatePdf(SpcySqsxLjzlMydBasic myd, boolean isDownPdf, HttpServletResponse response) throws IOException {
        String destWordUrl = "";
        try {
            destWordUrl = this.initMydTableTemplate(myd);
        }catch (Exception e){
            log.error("初始化-满意度调查问卷模板问卷错误：{}", e.getMessage());
        }

        if (StringUtils.isBlank(destWordUrl)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("问卷模板错误！");
            writer.close(); // 不要忘记关闭PrintWriter

            return;
        }

        // pdf保存路径
        if (isDownPdf) {
            String destPdfUrl = localFileUploadUtils.getTempFileRootUrl() + "/" + GetUuIdUtils.NotReplaceUuId() + ".pdf";
            WordPdfUtils.wordToPdf(destWordUrl, destPdfUrl);
            localFileUploadUtils.ejzLocalFileByZdyFile(new File(destPdfUrl), response);

        }else {
            localFileUploadUtils.ejzLocalFileByZdyFile(new File(destWordUrl), response);
        }
    }

    /**
     * 构建满意度调查问卷模板
     */
    public Result genMydTableTemplate(SpcySqsxLjzlMydBasic myd){
        String destWordUrl = "";
        try {
            destWordUrl = this.initMydTableTemplate(myd);
        }catch (Exception e){
            log.error("初始化-满意度调查问卷模板问卷错误：{}", e.getMessage());
        }

        if (StringUtils.isBlank(destWordUrl)){
            return Result.error("问卷模板错误！");
        }

        // pdf保存路径
        String wjccmc = GetUuIdUtils.NotReplaceUuId() + ".pdf";
        String destPdfUrl = localFileUploadUtils.getTempFileRootUrl() + "/" + wjccmc;
        WordPdfUtils.wordToPdf(destWordUrl, destPdfUrl);

        String cflj = "/" + DateConversionUtils.DateToMonthTwo(new Date()) + "/" + wjccmc;

        // minio文件上传
        boolean flag = busService.uploadMinioFileWjjl(cflj, destPdfUrl);
        if (flag) {
            busService.initSqsxWjjl(myd.getFsqsxid(), WjmlConstant.khmyddc, ".pdf", WjmlConstant.khmyddc + "-" + myd.getFqymc(), wjccmc, cflj);
        }else {
            return Result.error("文件上传错误！");
        }

        return Result.ok();
    }

}
